import { reactive, Ref, ref } from 'vue'

type Opts = {
  locale: string,
  messages: any
} 

let locale: Ref<string> = ref('')
let msg = reactive({
  data: ''
})

export function createI18n (options: Opts) {
  locale.value = options.locale
  msg.data = options.messages
  return {
    install: (app) => {
      // 注册一个全局可用的 $translate() 方法
      app.config.globalProperties.$translate = (key: string) => {
        return key.split('.').reduce((o, i) => {
          if (o) return o[i]
        }, msg.data[locale.value])
      }
    }
  }
}

export function changeLocale (lang: string) {
  locale.value = lang
}

export function changeMessages (param: string) {
  msg.data = param
}

export { locale }

export const messages = msg.data
